﻿using System;
using System.Linq;
using PTop.Code;
using PTop.Domain.Entity.Biz;
using PTop.Domain.IRepository.Biz;
using PTop.Repository.Biz;
using System.Collections.Generic;

namespace PTop.Application.Biz
{
    /// <summary>
    /// 意见App
    /// </summary>	
    public class MessageApp
    {
        private IMessageRepository service = new MessageRepository();

        public List<MessageEntity> GetList(Pagination pagination, string keyword)
        {
            var expression = ExtLinq.True<MessageEntity>();
            if (!string.IsNullOrEmpty(keyword))
            {
                expression = expression.And(t => t.F_Name.Contains(keyword));
                expression = expression.Or(t => t.F_Title.Contains(keyword));
                expression = expression.Or(t => t.F_Phone.Contains(keyword));
            }
            return service.FindList(expression, pagination);
        }

        public List<MessageEntity> GetListByOpenId(Pagination pagination, string openId)
        {
            var expression = ExtLinq.True<MessageEntity>();
            expression = expression.And(t => t.F_CreatorUserId == openId);
            return service.FindList(expression, pagination);
        }
        public MessageEntity GetForm(string keyValue)
        {
            return service.FindEntity(keyValue);
        }

        public void Delete(string keyValue)
        {
            service.Delete(t => t.F_Id == keyValue);
        }

        public void SubmitForm(MessageEntity entity, string keyValue)
        {
            if (!string.IsNullOrEmpty(keyValue))
            {
                var old = service.FindEntityWithNoTracking(m => m.F_Id == keyValue);
                if (!string.IsNullOrEmpty(entity.F_Response)
                    && old.F_Response != entity.F_Response)
                {
                    entity.F_ResponseTime = DateTime.Now;
                    new UserStatisticsApp().AddCount("F_MessageResponseCount");
                }
                entity.Modify(keyValue);
                service.Update(entity);
            }
            else
            {
                var openId = entity.F_CreatorUserId;
                entity.Create();
                entity.F_CreatorUserId = openId;
                if (entity.F_Response == null)
                {
                    entity.F_Response = Configs.GetValue("MessageAutoResponse");
                    entity.F_ResponseTime = DateTime.Now;
                }
                service.Insert(entity);
            }
        }

    }
}